package com.health.viewscontrols.medical.device.bp;

import android.bluetooth.BluetoothGatt;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleGattCallback;
import com.clj.fastble.callback.BleIndicateCallback;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleScanCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.utils.HexUtil;
import com.health.httpbean.model.BpModel;
import com.health.viewscontrols.medical.base.BaseDeviceActivity;
import com.nova.health.ble.callback.OnDeviceConnectChangedListener;
import com.novabluetooth.data.DeviceShowSaveData;
import com.novabluetooth.services.BluetoothConstant;
import com.novabluetooth.views.BlueToothConstant;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

import javax.security.auth.login.LoginException;

/**
 * 脉搏波血压计4.0
 */
public class BPYuyueActivity extends BaseDeviceActivity {

    public final static UUID UUID_SERVICE = UUID.fromString("00001810-0000-1000-8000-00805f9b34fb");
    public final static UUID UUID_NOTIFY = UUID.fromString("00002a36-0000-1000-8000-00805f9b34fb");
    public final static UUID UUID_Indicate = UUID.fromString("00002a35-0000-1000-8000-00805f9b34fb");

    private BleDevice fastBleDevice;

    @Override
    public void doBusiness() {
        tv_operation_tips.setText(com.nova.health.ble.R.string.bp_yuyue);
        BleManager.getInstance().init(getApplication());
        BleManager.getInstance()
                .enableLog(true)
                .setReConnectCount(1, 5000)
                .setConnectOverTime(10000)
                .setOperateTimeout(5000);

        startDevice();
    }

    @Override
    public void startDevice() {
        if (fastBleDevice == null) {
            showProgressDialog("正在连接" + deviceEnum.getTitle());
//            connectionPwBle();
            BleManager.getInstance().scan(new BleScanCallback() {
                @Override
                public void onScanStarted(boolean success) {
                }

                @Override
                public void onLeScan(BleDevice bleDevice) {
                    super.onLeScan(bleDevice);
                }

                @Override
                public void onScanning(BleDevice bleDevice) {
                    if (bleDevice != null && bleDevice.getMac() != null && deviceEnum.getMac().equals(bleDevice.getMac())) {
                        connectionPwBle();
                    }
                }

                @Override
                public void onScanFinished(List<BleDevice> scanResultList) {

                }
            });
        } else {
            ToastUtils.showShort("设备已连接，请等待测量结果");
            showProgressDialog("等待接收血压数据");
        }
    }

    private void connectionPwBle() {
        BleManager.getInstance().connect(deviceEnum.getMac(), new BleGattCallback() {
            @Override
            public void onStartConnect() {
                blueToothState.setText("蓝牙开始连接");
                showProgressDialog("正在连接血压设备");
            }

            @Override
            public void onConnectFail(BleDevice bleDevice, BleException exception) {
                Log.e(TAG, "onConnectFail: " +  exception.toString());
                blueToothState.setText("蓝牙连接失败");
                connectionPwBle();
            }

            @Override
            public void onConnectSuccess(final BleDevice bleDevice, BluetoothGatt gatt, int status) {
                //连接成功
                Log.e(TAG, "onConnectSuccess: " + bleDevice.getMac() );
                blueToothState.setText("蓝牙已连接");
                fastBleDevice = bleDevice;
                showProgressDialog("等待接收血压数据");
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getIndicate(bleDevice);
                    }
                },400);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getPwNotify(bleDevice);
                    }
                },1000);
            }

            @Override
            public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) {
                blueToothState.setText("蓝牙已断开连接");
                disconnectDevice();
                cancelProgressDialog();
            }
        });
    }

    private void getPwNotify(final BleDevice bleDevice) {
        BleManager.getInstance().notify(bleDevice,
                UUID_SERVICE.toString(),
                UUID_NOTIFY.toString(),
                new BleNotifyCallback() {
                    @Override
                    public void onNotifySuccess() {
                        Log.e(TAG, "onNotifySuccess: " );
                    }

                    @Override
                    public void onNotifyFailure(BleException exception) {
                        Log.e(TAG, "onNotifyFailure: " +exception.toString());
                    }

                    @Override
                    public void onCharacteristicChanged(byte[] data) {
                        //接收数据
                        String hexString = HexUtil.formatHexString(data);
                        Log.e(TAG, "onCharacteristicChanged: "+ hexString );
                        int bloodUp = Integer.parseInt(hexString.substring(4, 6) + hexString.substring(2, 4), 16);
                        tv_result.setText("实时数据: " + bloodUp + " /mmHg");
                    }
                });
    }

    private void getIndicate(final BleDevice bleDevice) {
        BleManager.getInstance().indicate(bleDevice, UUID_SERVICE.toString(), UUID_Indicate.toString(), new BleIndicateCallback() {
            @Override
            public void onIndicateSuccess() {
                Log.e(TAG, "onIndicateSuccess: " );
            }

            @Override
            public void onIndicateFailure(BleException exception) {

                Log.e(TAG, "onIndicateFailure: " + exception.toString() );
            }

            @Override
            public void onCharacteristicChanged(byte[] data) {
                Log.e(TAG, "onCharacteristicChanged: "+ data );
                //接收数据
                String hexString = HexUtil.formatHexString(data);
                Log.e(TAG, "onCharacteristicChanged: "+ hexString );
                update(hexString);
            }
        });
    }

    @Override
    public void update(String hexString) {
        try {
            Log.e(TAG, "update: " + hexString );
            int bloodUp = Integer.parseInt(hexString.substring(4, 6) + hexString.substring(2, 4), 16);
            int bloodDown = Integer.parseInt(hexString.substring(8, 10) + hexString.substring(6, 8), 16);
            int heart = Integer.parseInt(hexString.substring(16, 18) + hexString.substring(14, 16), 16);
//            int heart = Integer.parseInt(hexString.substring(34, 38), 16);
            Log.e(TAG, "高压: " + bloodUp + "mmHg  低压：" + bloodDown + "mmHg  心率：" + heart + "bpm");
            saveMaiboboData(bloodUp, bloodDown, heart);
//            if ("aa80020301010001".equals(hexString)) {
//                write(BlueToothConstant.START_DEVIC_COMMANDE);
//                Log.e(TAG, "血压计返回连接指令: " + hexString);
//            }else if("cc80020301010001".equals(hexString)) {
//                write(BlueToothConstant.START_DEVIC_COMMANDE);
//            } else if ("aa80020301020002".equals(hexString)) {
//                Log.e(TAG, "血压计返回启动测量指令: " + hexString);
//            } else if ("aa80020301030003".equals(hexString)) {
//                //血压计返回停止测量结果 断开连接
//                disconnectDevice();
//                Log.e(TAG, "血压计返回停止测量结果: 蓝牙主动断开连接");
//            } else {
//                String command = hexString.substring(10, 12);
//                if ("06".equals(command)) {
//                    int bloodUp = Integer.parseInt(hexString.substring(26, 30), 16);
//                    int bloodDown = Integer.parseInt(hexString.substring(30, 34), 16);
//                    int heart = Integer.parseInt(hexString.substring(34, 38), 16);
//                    Log.e(TAG, "高压: " + bloodUp + "  低压：" + bloodDown + "  心率：" + heart);
//                    saveMaiboboData(bloodUp, bloodDown, heart);
//                    //write(BlueToothConstant.CLOSE_DEVICE_COMMAND);
//                } else if ("05".equals(command)) {
//                    int realBloodPressure = Integer.parseInt(hexString.substring(20, 22), 16);
//                    tv_result.setText("实时数据: " + realBloodPressure + " /mmHg");
//                } else if ("07".equals(command)) {
//                    ToastUtils.showShort("测量错误,重新测量");
//                    disconnectDevice();
//                    tv_state.setText("测量错误,重新测量");
//                } else {
//                    Log.e(TAG, "notify: " + hexString);
//                }
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void saveMaiboboData(int bloodUp, int bloodDown, int heart) {
        try {
//            disconnectDevice();
            cancelProgressDialog();
            //收缩压、舒张压、心率
            String results = DeviceShowSaveData.getDataShow(bloodUp + ";" + bloodDown + ";" + heart + ";",
                    BluetoothConstant.XUEYA_YE680A_YUYUE);

            BpModel bpModel = new BpModel();
            bpModel.setHighpressure(bloodUp + "");
            bpModel.setLowvoltage(bloodDown + "");
            bpModel.setPulse(heart + "");
            DeviceShowSaveData.saveyuyueya(GsonUtils.toJson(bpModel));

            tv_result.setText("测量结果：\n        " + results);
            tv_state.setText("获取测量结果成功");
        } catch (Exception e) {
            Log.e(TAG, "报异常了: " + e.toString());
        }
    }

    @Override
    public void disconnectDevice() {
        try {
            cancelProgressDialog();
            fastBleDevice = null;
            BleManager.getInstance().disconnectAllDevice();
            BleManager.getInstance().destroy();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
